package org.dant.ant.extension.net.socket;

import java.io.*;
import java.net.*;
import org.dant.ant.extension.tasks.internal.RemoteResponse;
import org.dant.ant.extension.tasks.internal.RemoteCommand;
import org.dant.ant.extension.tasks.internal.Endpoint;
import org.dant.ant.extension.net.NetConstants;

public class SocketClient {

  private String host;
  private int port;
  
  public SocketClient(Endpoint ep) {
    host = ep.getIp();
    if (host == null) host = ep.getHostname();
    if (host == null) host = NetConstants.DEFAULT_LOCAL_IP;
    port = (ep.getPort()==null) ? NetConstants.DEFAULT_SOCKET_PORT : Integer.parseInt(ep.getPort());
  }
  
  public RemoteResponse remoteCall(RemoteCommand request) throws Exception {
    Socket client = new Socket(host, port);
    ObjectOutputStream objOut = new ObjectOutputStream(client.getOutputStream());
    ObjectInputStream objIn = new ObjectInputStream(client.getInputStream());
    objOut.writeObject(request);
    objOut.flush();
    RemoteResponse response = (RemoteResponse) objIn.readObject();
    objIn.close();
    objOut.close();
    return response;
  }
}
